// 将时间长度转成多少h多少s
function convertMillicountsToHMS(time) {
  let seconds = Math.floor(time);
  let minutes = Math.floor(seconds / 60);
  let hours = Math.floor(minutes / 60);

  seconds %= 60;
  minutes %= 60;
  // hours %= 24;

  // console.log('hours',hours,'minutes',minutes,'seconds',seconds)
  // 将小时、分钟、秒转换为字符串并保证至少有两位数字
  let hourStr = ("0" + hours).slice(-2);
  let minuteStr = ("0" + minutes).slice(-2);
  let countstr = ("0" + seconds).slice(-2);

  if (hours > 0) {
    return `${hourStr}:${minuteStr}:${countstr}`;
  }

  return `${minuteStr}:${countstr}`;
}

// 获取每个刻度线之间的多少秒（画刻度）
const getScaleLineMinute = (time) => {
  let seconds = Math.floor(time);
  let minutes = Math.floor(seconds / 60);
  let hours = Math.floor(minutes / 60);
  // 假设容器是1000px

  // 秒
  if (minutes < 1) {
    return 1;
  }

  // 分钟
  if (hours <= 1) {
    // 是5的倍数
    const scale = Math.floor(minutes / 5);
    // 1分钟一个刻度
    return scale <= 0 ? 5 : scale * 15;
  }

  // 小时
  if (hours > 1) {
    // 是5的倍数
    const scale = Math.floor(hours / 5);
    // 30分钟一个刻度
    return scale <= 0 ? 10 * 60 : scale * 30 * 60;
  }

  return 1;
};

// 绘画配置
const Colors = {
  color: "#fff",
  background: "#333", //背景
  markColor: "rgba(64,158,255,0.5)",

  //中间线
  meddleLine: "#33CC33",
  //移动线
  moveLine: "#808080",
  //移动时间
  moveDate: "#009966",
  //刻度线
  scaleLine: "#808080",
};

class Ruler {
  /**
   * 初始化刻度尺插件
   * @el 容器 String
   * @height 刻度尺高度 Number
   * @time 绘画的时长 Number
   * */
  constructor(params) {
    // 构建函数传参
    const { time, el, height, changeRegions, addTempPosition } = params;

    this.canvas = el;
    this.canvasWidth = 0; // 容器宽度
    this.height = height; // 容器高度
    this.px_second = 0; // 每个像素点对应多少秒（像素转时间和刻度）
    this.ctx = this.canvas.getContext("2d"); // canvas 上下文
    this.time = time; // 秒数
    this.scaleLine_second = getScaleLineMinute(time); // 1 个刻度代表1s

    this.mousePositions = []; //  鼠标点击两次的距离合集
    this.markList = []; //  点击打框

    // 移动时鼠标有没有按下
    this.mouseDown = false;
    // 鼠标按下时有没有移动
    this.isMove = false;

    // 监听事件
    this.listenEvents();

    this.changeRegions = changeRegions; // 更新事件
    this.addTempPosition = addTempPosition; // 画第一条刻度
  }

  init() {
    if (this.time === 0 || !this.scaleLine_second) {
      // console.error("时间为0");
      return;
    }
    // 1. 计算像素和时间比
    const winWidth = this.canvas.parentElement.clientWidth;
    console.log("容器宽度", winWidth);
    this.canvas.style.width = `${winWidth}px`;
    this.canvas.style.height = `${this.height}px`;

    // 设置画布大小
    this.canvas.width = winWidth;
    this.canvas.height = this.height;

    this.canvasWidth = winWidth;
    this.px_second = this.time / winWidth;
    // NOTE 当前时间/总时长 = 当前offetX/总长度

    // 2. 绘制图表
    this.draw();
  }

  listenEvents() {
    // 鼠标悬浮事件
    this.canvas.addEventListener("mousemove", (e) => {
      this.mousemove(e);
    });
    // resize 事件
    window.addEventListener(
      "resize",
      () => {
        this.resize();
      },
      false
    );
    // 鼠标点击事件
    this.canvas.addEventListener("mousedown", (e) => {
      this.mousedown(e);
    });
    this.canvas.addEventListener("mouseup", (e) => {
      this.mouseup(e);
    });
    this.canvas.addEventListener("mouseleave", (e) => {
      this.mouseleave(e);
    });
  }

  disposed() {
    // 注销事件监听
    this.canvas.onmousemove = null;
    window.onresize = null;
  }

  draw() {
    //重置高宽清空画布
    this.canvas.width = this.canvas.width;
    this.canvas.height = this.canvas.height;
    this.drawScaleLine();
    this.drawMark();
  }

  drawScaleLine() {
    const ctx = this.ctx;
    //刻度尺背景
    ctx.fillStyle = Colors.background;
    ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
    ctx.font = "14px Arial";
    ctx.fillStyle = Colors.color;
    ctx.textAlign = "center";
    ctx.textBaseline = "middle";

    // 每条线之间的间隔 scaleLine_second来确定每个格代表多长时间
    const line_px = this.scaleLine_second / this.px_second;
    // console.log("line_px", line_px, "this.canvas.width", this.canvas.width);
    let count = 0;
    //画刻度线
    for (let i = 0; i < this.canvasWidth; i += line_px) {
      ctx.beginPath();
      ctx.save();
      ctx.strokeStyle = Colors.color;
      ctx.lineWidth = 1;
      ctx.lineCap = "round";
      // 绘制的x坐标
      const x = i;

      ctx.moveTo(x, 0);
      ctx.lineTo(x, Math.floor(this.height * 0.3));

      const time = count * this.scaleLine_second;

      // 获取绘制的点 秒的时候相隔5
      const bool =
        this.scaleLine_second === 1
          ? count % 5 === 0 || count % 10 === 0
          : true;
      if (bool) {
        ctx.lineTo(x, Math.floor(this.height * 0.35));

        // 添加文字
        ctx.fillText(
          convertMillicountsToHMS(time),
          x,
          Math.floor(this.height * 0.55)
        );
      }

      ctx.stroke();
      // ctx.restore();
      // ctx.closePath();

      count++; // 计算刻度数
    }
  }

  // 画标记的时间
  drawMark() {
    const ctx = this.ctx;

    // 画canvas上部分的颜色
    this.markList.forEach((item) => {
      ctx.fillStyle = item.bgColor || Colors.markColor;
      const { startTime, endTime } = item;
      const start = Math.floor(startTime / this.px_second);
      const end = Math.floor(endTime / this.px_second);
      ctx.fillRect(start, 0, end - start, this.height * 0.5);
    });
    ctx.save();
  }

  // 画鼠标移上去的线
  mousemove(e) {
    this.draw();

    if (this.mouseDown) {
      // this.mouseDownMove(e);
      this.isMove = true;
    }

    let offetTime = Math.floor(e.offsetX * this.px_second);

    const time = convertMillicountsToHMS(offetTime);
    const ctx = this.ctx;
    if (!ctx) {
      return;
    }

    ctx.beginPath();
    ctx.moveTo(e.offsetX - 1, 0);
    ctx.lineTo(e.offsetX - 1, Math.floor(this.height * 0.8));
    ctx.strokeStyle = Colors.moveLine;
    ctx.lineWidth = 1;
    ctx.stroke();
    ctx.fillStyle = Colors.moveDate;

    ctx.font = `${12}px serif`;
    ctx.fillText(time, e.offsetX - 50, Math.floor(this.height * 0.7));
  }

  // 鼠标按下
  mousedown(e) {
    if (!e.offsetX){
      return
    }
    this.mouseDown = true;
    this.isMove = false;
    this.mousePositions.push(e.offsetX);

    if (this.mousePositions.length === 1) {
      // 绘制刻度线第一条
      this.addTempPosition && this.addTempPosition(e.offsetX);
    } else {
      this.addTempPosition && this.addTempPosition(0);
    }
  }

  // 抬起鼠标
  mouseup(e) {
    this.mouseDown = false;
    // 没有滑动或鼠标移动(视为点击操作)，就渲染中间时间（另外的是在移动事件里渲染）。
    if (!this.isMove && this.mousePositions.length === 2) {
      const startTime = this.mousePositions[0] * this.px_second;
      const endTime = this.mousePositions[1] * this.px_second;
      console.log(
        "startTime",
        startTime,
        "endTime",
        endTime,
        this.mousePositions
      );

      this.markList.push({
        startTime,
        endTime,
      });

      // 重新制为0
      this.mousePositions = [];
      this.draw();
      // 释放时确定时间选择
      this.changeRegions(this.markList);
    }
  }

  //鼠标离开
  mouseleave(e) {
    this.draw();
    //鼠标离开无法在触发mouseup，所以当拖动时将离开视释放
    if (this.mouseDown) {
      this.mouseup(e);
    } else {
      this.mouseDown = false;
    }
  }

  resize() {
    //有时屏幕尺寸变化了，而容器的尺寸还未改变的情况下的处理
    if (
      this.canvas.style.width ===
      this.canvas.parentElement.clientWidth + "px"
    ) {
      setTimeout(() => {
        this.resize();
      }, 10);
    } else {
      //重新初始化
      this.init();
    }
  }

  setTime(time){
    this.time = time;
    this.init();
  }
}
